import Vector3Ex from "./Vector3Ex";

export class CameraEx {

    static ScreenPosToWorldPos(camera: Laya.Camera, screenPos: Laya.Vector2, fakeYPos: number): Laya.Vector3 {
        let ray = new Laya.Ray(Vector3Ex.zero, Vector3Ex.zero);
        camera.viewportPointToRay(screenPos, ray);
        let downVec = Vector3Ex.s_down;
        let dotValue = Vector3Ex.Dot(downVec, ray.direction);
        let heightValue = ray.origin.y;
        let scaleValue = heightValue / dotValue;
        let finalDir = Vector3Ex.Scale(ray.direction, scaleValue);
        return Vector3Ex.Add(ray.origin, finalDir);
    }

    /**
     * 获取3d物件在屏幕中的位置
     * @param camera 
     * @param pos3d 
     * @param ui 
     */
    public static GetPointFrom3DWorld(camera: Laya.Camera, pos3d: Laya.Vector3, out: Laya.Vector4, ui?: fgui.GObject): Laya.Point {
        let uiPos = out || new Laya.Vector4();
        camera.worldToViewportPoint(pos3d, uiPos);
        if (ui != null) {
            return ui.globalToLocal(uiPos.x, uiPos.y);
        } else {
            return new Laya.Point(uiPos.x, uiPos.y);
        }
    }

    static ScreenPosToRay(camera: Laya.Camera, screenPos: Laya.Vector2, ray?: Laya.Ray): Laya.Ray {
        ray = ray || new Laya.Ray(Vector3Ex.zero, Vector3Ex.zero);
        let clickPoint = new Laya.Vector2(screenPos.x / Laya.stage.width, screenPos.y / Laya.stage.height);
        camera.normalizedViewportPointToRay(clickPoint, ray);
        return ray;
    }
}